package com.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.app.vo.ElectronicVo;
import com.app.vo.TypeVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api/type")
public class TypeController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private PersonService personService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DepartmentService departmentService;

    @GetMapping("/getDropList")//下拉框查询
    public Result<Object> getDropList(
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        CategoryVo vo = new CategoryVo();

        List<CategoryModel> categoryModelList = categoryService.getCategoryByPid(26);
        vo.setTypeList(categoryModelList);//型号类型
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());
        List<PersonModel> personList = personService.otherPersonList(idList);
        if (personList != null && personList.size() > 0) {
            vo.setPersonList(personList);
        }
        return Result.success(vo);
    }

    @GetMapping("/getTypeList")//型号管理分页查询
    public Result<Object> getTypeList(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer departmentId,
            HttpServletRequest request
            , Integer sortType) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());

        Page<TypeModel> typeModelPage = typeService.getPageTypeList(page, limit, name, departmentId, idList,sortType);
        for (int i = 0; i < typeModelPage.getRecords().size(); i++) {
            if (typeModelPage.getRecords().get(i).getDepartmentId() != null) {
                DepartmentModel departmentModel = departmentService.getDepByDepId((typeModelPage.getRecords().get(i).getDepartmentId()));
                if (departmentModel != null) {
                    typeModelPage.getRecords().get(i).setDepartmentText(departmentModel.getName());//获取部门名字
                }
            }
        }
        if (typeModelPage.getRecords() == null) {
            return Result.error(200, "暂无数据");
        }
        int count = (int) typeModelPage.getTotal();
        List<TypeModel> typeModelList;
        typeModelList = typeModelPage.getRecords();
        TypeVo vo = new TypeVo();
        vo.setCount(count);
        vo.setList(typeModelList);
        return Result.success(vo);
    }

    @PostMapping("/insertType")//    新增/修改型号管理
    public Result<Object> insertType(
            @RequestBody TypeModel typeModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (typeModel.getId() > 0) {
            typeModel.setUpdateTime(CommonHelp.getNowTimestamp());
            typeService.update(typeModel);
        } else {
            typeModel.setCreateTime(CommonHelp.getNowTimestamp());
            typeService.insert(typeModel);
        }
        return Result.success(null);
    }


    @GetMapping("/deleteById")//删除型号
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        TypeModel typeModel = typeService.getTypeByTypeId(id);
        if (typeModel == null) {
            return Result.error(500, "该角色不存在");
        } else {
            typeService.delete(id);
            return Result.success(null);
        }
    }

    /**
     * 批量删除实验记录
     */
    @DeleteMapping("/deleteTypeBatchByIds")
    public Result<Object> deleteBatchById(@RequestParam("ids") String ids, HttpServletRequest request) {
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        // 执行批量删除操作
        return typeService.deleteTypeBatchByIds(ids);
    }

    // 校验token并获取用户信息的方法
    private AdminUserModel validateTokenAndGetUser(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            throw new IllegalArgumentException("token不存在");
        }
        String userId = TokenUtils.verify(token);
        return adminUserService.getUserByUserId(Integer.parseInt(userId));
    }
}
